<template>
  <div class="orderTemplate">
    <div class="startProcess" v-if="!processIng">
      <table ref="dataTable" cellpadding="10" cellspacing="0">
        <tr>
          <td colspan="10" class="title">运单支付申请表</td>
        </tr>
        <tr>
          <td colspan="2">申请时间</td>
          <td colspan="3">{{row.apply_time.replace('-','年').replace('-','月')}}日</td>
          <td colspan="2">货主名称</td>
          <td colspan="3">{{row.company_name}}</td>
        </tr>
        <tr>
          <td colspan="10" class="title">运单信息</td>
        </tr>
        <tr>
          <td>运单号</td>
          <td>{{row.add_id}}-{{ row.id }}</td>
          <td>货物名称</td>
          <td>{{row.goods}}</td>
          <td>接单时间</td>
          <td colspan="2">{{row.add_time}}</td>
          <td>卸货时间</td>
          <td colspan="2">{{row.dd_time}}</td>
        </tr>
        <tr>
          <td>发货地址</td>
          <td colspan="4">{{row.ship_address}} {{ row.detail_address }}</td>
          <td>卸货地址</td>
          <td colspan="4">{{row.to_address}} {{ row.to_detail_address }}</td>
        </tr>
        <tr>
          <td>装货吨数</td>
          <td>{{row.kg}}</td>
          <td>卸货吨数</td>
          <td>{{row.unloading_weight}}</td>
          <td>亏损重量</td>
          <td>{{row.loss_weight}}</td>
          <td>运费单价</td>
          <td colspan="2">{{row.unit_price}}</td>
          <td>含/不含 税</td>
        </tr>
        <tr>
          <td>备注</td>
          <td colspan="9"></td>
        </tr>
        <tr>
          <td colspan="10" class="title">运力信息</td>
        </tr>
        <tr>
          <td>司机姓名</td>
          <td colspan="2">{{row.sjxm}}</td>
          <td>车牌号码</td>
          <td colspan="2">{{row.cph}}</td>
          <td>联系方式</td>
          <td colspan="3">{{row.mobile}}</td>
        </tr>

        <tr>
          <td colspan="10" class="title">收款信息</td>
        </tr>
        <tr>
          <td>收款人</td>
          <td colspan="2">{{row.user_name}}</td>
          <td>账号</td>
          <td colspan="3">{{row.bank_number}}</td>
          <td>开户行</td>
          <td colspan="2">{{row.bank_name}}</td>
        </tr>
        <tr>
          <td colspan="10" class="title">结算信息</td>
        </tr>
        <tr>
          <td colspan="2">回单</td>
          <td>已收( )</td>
          <td>未收( )</td>
          <td>装车费</td>
          <td>{{row.loading_charge}}</td>
          <td>卸车费</td>
          <td>{{row.unloading_charge}}</td>
          <td>信息费</td>
          <td>{{row.information_cost}}</td>
        </tr>
        <tr>
          <td>油卡</td>
          <td>0</td>
          <td>保险</td>
          <td>{{row.insurance_expense}}</td>
          <td>押金</td>
          <td colspan="2">{{row.deposit_charge}}</td>
          <td>含税金额</td>
          <td colspan="2" style="padding:5px">
            <el-input v-model="startForm.bill_money" type="number" placeholder="请输入含税金额"></el-input>
          </td>
        </tr>
        <tr>
          <td>应结运费</td>
          <td>{{row.price}}</td>
          <td>运费扣减</td>
          <td></td>
          <td>预付运费</td>
          <td colspan="2"></td>
          <td>实结运费</td>
          <td colspan="2" style="padding:5px">
            <el-input v-model="startForm.money" type="number" placeholder="请输入实结运费"></el-input>
          </td>
        </tr>

        <!-- <tr>
        <td colspan="10" class="title">结算审批流程</td>
      </tr>
      <tr>
        <td colspan="2">部门</td>
        <td colspan="2">审核情况</td>
        <td colspan="2">签字</td>
        <td colspan="2">时间</td>
        <td colspan="2">备注</td>
      </tr>
      <tr>
        <td colspan="2">开单人</td>
        <td colspan="2"></td>
        <td colspan="2"></td>
        <td colspan="2"></td>
        <td colspan="2"></td>
      </tr>
      <tr>
        <td colspan="2">跟踪人员</td>
        <td colspan="2"></td>
        <td colspan="2"></td>
        <td colspan="2"></td>
        <td colspan="2"></td>
      </tr>
      <tr>
        <td colspan="2">平台客服</td>
        <td colspan="2"></td>
        <td colspan="2"></td>
        <td colspan="2"></td>
        <td colspan="2"></td>
      </tr>
      <tr>
        <td colspan="2">财务负责人</td>
        <td colspan="2"></td>
        <td colspan="2"></td>
        <td colspan="2"></td>
        <td colspan="2"></td>
      </tr>
      <tr>
        <td colspan="2">出纳专员</td>
        <td colspan="2"></td>
        <td colspan="2"></td>
        <td colspan="2"></td>
        <td colspan="2"></td>
      </tr>
      <tr>
        <td colspan="2">董事长</td>
        <td colspan="2"></td>
        <td colspan="2"></td>
        <td colspan="2"></td>
        <td colspan="2"></td>
        </tr>-->
      </table>
      <div class="tool">
        <el-button
          size="mini"
          type="primary"
          style="margin-bottom: 10px;"
          @click="startProcess"
        >发起审批</el-button>
      </div>
    </div>

    <div class="processIng" v-if="processIng">
      <div class="left">
        <div class="descInfo" v-if="false">
          <p class="item">公司名: {{approveInfo.company}}</p>
          <p class="item">运单ID: {{approveInfo.add_id}}-{{approveInfo.yund_id}}</p>
          <!-- <p class="item">司机名称: {{approveInfo.driver_name}}</p> -->
          <p class="item">车牌号: {{approveInfo.cph}}</p>
          <p class="item">收货重量: {{approveInfo.shkg}}吨</p>
          <p class="item">
            含税金额:
            <span style="color: green;">{{approveInfo.money_bill}}</span> 元
          </p>

          <p class="item">
            支付金额:
            <span style="color: red;">{{approveInfo.money}}</span> 元
          </p>
        </div>
        <div class="process">
          <div class="process-item" v-for="(item,index) in userStatusList" :key="index">
            <div :class="{leftLine:true,last:isLast(index),disable:item.approveStatus == 0}">
              <div class="status">
                <span
                  v-if="item.approveStatus != 0"
                  :class="{icon:true,success:item.approveStatus == 1,wait:item.approveStatus == 2}"
                ></span>
              </div>
            </div>

            <div class="process-item-title">{{item.approveName}}</div>
            <div class="process-item-status">
              <span class="userName">{{item.userName}}</span>
              {{statusMap(item.approveStatus)}}
              <!-- <el-button
              v-if="item.approveStatus == 2 && showSignBtn"
              class="signBtn"
              type="primary"
              @click="toSign"
              >签名审批</el-button>-->
              <el-image
                v-if="index != 0 && item.approveStatus == 1 && item.svgImg"
                class="sign"
                :src="item.svgImg"
                :preview-src-list="[item.svgImg]"
              ></el-image>
              <!-- 当财务部已审批后出现微信审批按钮 -->
              <!-- 显示条件:当前节点为财务部且已审批且董事长还未审批 -->
              <el-button
              v-if="item.approveName == '财务部' && item.approveStatus == 1 && !isEnd"
               style="margin-left: 10px;font-size:12px;width:80px;height:30px" 
               type="primary" 
               size="mini" @click="sendWechat">发送微信</el-button>

            </div>
            <div class="process-item-desc" v-if="item.signTime">{{item.signTime}}</div>
          </div>
        </div>
      </div>
      <div class="right">
        <table ref="dataTable" cellpadding="10" cellspacing="0">
          <tr>
            <td colspan="10" class="title">运单支付申请表</td>
          </tr>
          <tr>
            <td colspan="2">申请时间</td>
            <td colspan="3">{{row.apply_time.replace('-','年').replace('-','月')}}日</td>
            <td colspan="2">货主名称</td>
            <td colspan="3">{{row.company_name}}</td>
          </tr>
          <tr>
            <td colspan="10" class="title">运单信息</td>
          </tr>
          <tr>
            <td>运单号</td>
            <td>{{row.add_id}}-{{ row.id }}</td>
            <td>货物名称</td>
            <td>{{row.goods}}</td>
            <td>接单时间</td>
            <td colspan="2">{{row.add_time}}</td>
            <td>卸货时间</td>
            <td colspan="2">{{row.dd_time}}</td>
          </tr>
          <tr>
            <td>发货地址</td>
            <td colspan="4">{{row.ship_address}} {{ row.detail_address }}</td>
            <td>卸货地址</td>
            <td colspan="4">{{row.to_address}} {{ row.to_detail_address }}</td>
          </tr>
          <tr>
            <td>装货吨数</td>
            <td>{{row.kg}}</td>
            <td>卸货吨数</td>
            <td>{{row.unloading_weight}}</td>
            <td>亏损重量</td>
            <td>{{row.loss_weight}}</td>
            <td>运费单价</td>
            <td colspan="2">{{row.unit_price}}</td>
            <td>含/不含 税</td>
          </tr>
          <tr>
            <td>备注</td>
            <td colspan="9"></td>
          </tr>
          <tr>
            <td colspan="10" class="title">运力信息</td>
          </tr>
          <tr>
            <td>司机姓名</td>
            <td colspan="2">{{row.sjxm}}</td>
            <td>车牌号码</td>
            <td colspan="2">{{row.cph}}</td>
            <td>联系方式</td>
            <td colspan="3">{{row.mobile}}</td>
          </tr>

          <tr>
            <td colspan="10" class="title">收款信息</td>
          </tr>
          <tr>
            <td>收款人</td>
            <td colspan="2">{{row.user_name}}</td>
            <td>账号</td>
            <td colspan="3">{{row.bank_number}}</td>
            <td>开户行</td>
            <td colspan="2">{{row.bank_name}}</td>
          </tr>
          <tr>
            <td colspan="10" class="title">结算信息</td>
          </tr>
          <tr>
            <td colspan="2">回单</td>
            <td>已收( )</td>
            <td>未收( )</td>
            <td>装车费</td>
            <td>{{row.loading_charge}}</td>
            <td>卸车费</td>
            <td>{{row.unloading_charge}}</td>
            <td>信息费</td>
            <td>{{row.information_cost}}</td>
          </tr>
          <tr>
            <td>油卡</td>
            <td>0</td>
            <td>保险</td>
            <td>{{row.insurance_expense}}</td>
            <td>押金</td>
            <td colspan="2">{{row.deposit_charge}}</td>
            <td>含税金额</td>
            <td colspan="2" style="padding:5px">
              <!-- <el-input v-model="startForm.bill_money" type="number" placeholder="请输入含税金额"></el-input> -->
              {{ approveInfo.money_bill }}
            </td>
          </tr>
          <tr>
            <td>应结运费</td>
            <td>{{row.price}}</td>
            <td>运费扣减</td>
            <td></td>
            <td>预付运费</td>
            <td colspan="2"></td>
            <td>实结金额</td>
            <td colspan="2" style="padding:5px">
              <!-- <el-input v-model="startForm.money" type="number" placeholder="请输入实结运费"></el-input> -->
              {{ approveInfo.money }}
            </td>
          </tr>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import {
  submitApplication,
  getApproveBillDetail,
  getApproveRoleList,
  pushUserWechat
} from "@/api/waybill";
export default {
  name: "orderTemplate",
  props: {
    row: {
      default: {},
      type: Object
    }
  },
  data() {
    return {
      processIng: false,
      startForm: {
        company: "", //公司名称
        add_id: "", //总运单id
        yund_id: "", //运单id
        money: "", //结算金额
        bill_money: "", //含税金额
        cph: "", //车牌号
        weight: "", //收货重量
        driver_name: "" //司机姓名
      },
      userStatusList: [],
      userInfo: null, //当前审批人信息
      approveInfo: {}, //当前运单审批信息
      isEnd:false,//是否全部流程审批结束
    };
  },
  mounted() {
    if (this.row && this.row.orderInfo.apply_bill_status > 0) {
      //已经发起审批
      this.processIng = true;
    }
    this.initial();
  },
  methods: {
    async initial() {
      if (!this.processIng) return;
      let yund_id = this.row.orderInfo.id;
      //获取当前审批流程详情
      let billDetail = await getApproveBillDetail({
        yund_id
      });
      if (billDetail.code == 200) {
        this.approveInfo = billDetail.data;
        console.log("审批流程详情", this.approveInfo);

        //获取所有用户列表
        let userListInfo = await getApproveRoleList();
        // console.log("所有用户数据", userListInfo);

        if (userListInfo.code == 200) {
          let userList = userListInfo.data;
          //获取当前的流程节点状态 然后从对应的用户列表中匹配查询
          let status = this.approveInfo.status;
          status = status + 1; //流程节点状态+1则为当前节点
          let currentUserInfo = {};
          let lastLen = Object.keys(userList).length;
          if (status > lastLen) {
            //全部审批流程已经全部结束 取最后节点
            this.isEnd = true;//标记流程结束 用于判断是否显示财务部的微信审批按钮
            currentUserInfo = userList[lastLen].role_list;
          } else {
            //处于审批流程某一节点
            currentUserInfo = userList[status].role_list;
          }

          //根据获取的openid来查找当前审批的用户信息
          this.userInfo = currentUserInfo.find(item => {
            return item.openId == this.openId;
          });
 
          if (!this.userInfo) {
            //没有匹配到对应的用户 不显示审批按钮
            this.showSignBtn = false;
          }

          //生成渲染路程节点列表
          this.userStatusList = Object.keys(userList).map(item => {
            let _status = item;
            let role_list = userList[item].role_list;
            let role_name = userList[item].role_name;
            let keyName = "status" + _status + "_name";
            let keyTime = "status" + _status + "_time";
            let userName = this.approveInfo[keyName];
            let signTime = this.approveInfo[keyTime];
            let signImg = "",
              svgImg = "";
            if (Number(_status) < status && userName) {
              //已经审批 存在签名
              let item = role_list.find(item => {
                return item.user_name == userName;
              });
              if (item) {
                signImg = item.sign_img;
                svgImg = decodeURIComponent(item.svg_img);
              }
            }
            //取所有用户列表中
            return {
              approveName: role_name,
              approveStatus: _status == status ? 2 : _status < status ? 1 : 0,
              userName,
              signTime,
              signImg,
              svgImg
            };
          });
          console.log("this.userStatusList", this.userStatusList);
        }
      }
    },
    statusMap(status) {
      if (status == 0) {
        return "待审批";
      }
      if (status == 1) {
        return "已审批";
      }
      if (status == 2) {
        return "审批中";
      }
    },
    isLast(index) {
      return index == this.userStatusList.length - 1;
    },
    async startProcess() {
      if (!this.startForm.money) {
        this.$message.error("请输入实结金额!");
        return;
      }
      if (!this.startForm.bill_money) {
        this.$message.error("请输入含税金额!");
        return;
      }
      if(this.startForm.money >= this.startForm.bill_money){
        this.$message.error("含税金额必须大于实结金额!");
        return;
      }

      this.startForm.company = this.row.orderInfo.company_name;
      this.startForm.add_id = this.row.orderInfo.add_id;
      this.startForm.yund_id = this.row.orderInfo.id;
      this.startForm.cph = this.row.orderInfo.cph;
      this.startForm.weight = this.row.orderInfo.weight;
      this.startForm.driver_name = this.row.orderInfo.sj_name;
      console.log("this.startForm", this.startForm);

      const loading = this.$loading({
        lock: true,
        text: "发起审批中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let result = await submitApplication(this.startForm);
      loading.close();
      if (result.code == 200) {
        this.$message.success("发起审批成功!");
        setTimeout(() => {
          this.$emit("refreshTable");
        }, 500);
      }
    },
    //财务部审批后发送微信
    sendWechat(){
      this.$confirm('确定要发送微信吗？', '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(async () => {
          let result = await pushUserWechat({
            batch_number:this.approveInfo.batch_number
          });
          if(result.code == 200){
            this.$message.success('发信微信成功');
          }
        }).catch(() => { });
    },
    download() {
      const loading = this.$setLoading("下载中...");
      html2canvas(this.$refs.dataTable, {
        scale: 4,
        background: "#ffffff"
      }).then(canvas => {
        loading.close();
        var contentWidth = canvas.width; //获取Canvas(上面元素id 'layout-wrapper')对象的宽度
        var contentHeight = canvas.height; //获取Canvas(上面元素id 'layout-wrapper')对象的高度
        console.log("contentWidth", contentWidth);
        console.log("contentHeight", contentHeight);
        // 创建jsPDF对象
        const pdf = new jsPDF("a4", "pt", [contentWidth, contentHeight]); //创建一个新的PDF对象，参数包括页面格式（'1'表示A4纸张）、单位（'pt'）和页面尺寸（[contentWidth, contentHeight]）
        var pageData = canvas.toDataURL("image/jpeg", 1.0); //将Canvas对象转换为JPEG格式的数据，并将其存储在pageData变量中。1.0表示图片质量
        pdf.addImage(pageData, "JPEG", 0, 0, contentWidth, contentHeight); //将JPEG格式的图片添加到PDF文件中，图片的左上角坐标为(0, 0)，宽度为contentWidth，高度为contentHeight
        pdf.save(
          `运单模版${this.row.apply_time
            .replace("-", "年")
            .replace("-", "月")} ${this.row.add_id}-${this.row.id}.pdf`
        );
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.orderTemplate {
  color: #000;
  ::v-deep .el-input__inner {
    height: 30px;
  }
  .area {
    padding: 10px;
  }
  table {
    margin: 0 auto;
    width: 1000px;
    border-right: 1px solid #000000;
    border-bottom: 1px solid #000000;
  }

  table td {
    border-left: 1px solid #000000;
    border-top: 1px solid #000000;
    padding: 10px;
    text-align: center;
  }

  .title {
    font-weight: bold;
  }
  .tool {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
  .processIng {
    display: flex;
    .left {
      width: 25%;
      padding-left: 50px;
    }
    .right {
      flex: 1;
      // display: flex;
      // justify-content: center;
    }
    .process {
      margin: 0 auto;
    }
    .descInfo {
      width: 70%;
      // margin-left: 20%;
      margin-bottom: 10px;
      /* display: flex; */
      flex-wrap: wrap;
      .item {
        /* padding-left: 1rem; */
        box-sizing: border-box;
        width: 100%;
        margin-bottom: 5px;
        color: #858585;
      }
    }
    .process-item {
      padding-bottom: 30px;
      padding-left: 20px;
      position: relative;
      .process-item-title {
        color: #000;
        font-weight: bold;
        margin-bottom: 5px;
        font-size: 16px;
      }
      .process-item-status {
        color: #353535;
        margin-bottom: 5px;
        display: flex;
        font-size: 14px;
        .userName {
          font-weight: bold;
          margin-right: 5px;
        }
        .sign {
          width: 80px;
          height: 30px;
          margin-left: 20px;
        }
      }
      .process-item-desc {
        color: #898989;
      }

      .leftLine {
        position: absolute;
        height: 100%;
        width: 4px;
        background-color: #20b759;
        left: 0;
        .status {
          width: 16px;
          height: 16px;
          background-color: #20b759;
          border-radius: 100%;
          position: absolute;
          left: -6px;
          // top: 0.1rem;
          .icon {
            display: block;
            width: 100%;
            height: 100%;
            background-color: #fff;
            background-size: 100%;
          }
          .wait {
            background-image: url(@/assets/images/wait.png);
          }
          .success {
            background-image: url(@/assets/images/success.png);
          }
        }
      }
      .disable {
        background-color: #d1d1d1;
        .status {
          background-color: #d1d1d1;
        }
      }
      .last {
        background-color: transparent;
      }
    }
  }
}
</style>
